import axios from 'axios'
import iView from 'iview'

function getErrorMessage (error) {
  if (error.response) {
    if (error.response.data) {
      return error.response.data.message
    } else {
      return error.response.status
    }
  }
  return error
}

function formatError (error) {
  if (error.response) {
    if (error.response.data) {
      let text = error.response.data.code + ', ' + error.response.data.message
      return text
    } else {
      return error.response.status
    }
  }
  return error
}

export default {
  /**
   * 设置API路径
   * @param {string} url API路径
   */
  setApiUrl (url) {
    axios.defaults.baseURL = url
  },

  /**
   * 设置Basic 认证
   * @param {string} username
   * @param {string} password
   */
  setBasicAuthorization (username, password) {
    axios.defaults.headers.common['Authorization'] = 'Basic ' + window.btoa(`${username}:${password}`)
  },

  /**
   * 清理认证
   */
  clearAuthorization () {
    delete axios.defaults.headers.common['Authorization']
  },

  setBearerAuthorization (token) {
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
  },

  getErrorMessage,
  formatError,

  errorHandler (error) {
    if (error.response && error.response.data) {
      iView.Message.error(error.response.data.message)
    } else if (error.message) {
      iView.Message.error(error.message)
    } else {
      iView.Message.error(error)
    }
  }
}
